//app.js
App({
  globalData: {
    baseUrl: 'https://www.pzhdqzgh.com',
    // baseUrl: 'https://localhost',
    openid: "",
    userInfo: "",
  },
  onLaunch: function () {
    var that = this;  
    wx.getUserInfo({
      success: function (res) {
        console.log('获取用户授权成功')
        var userInfo = res.userInfo;
        that.globalData.userInfo = userInfo;
        that.login();
      },
      fail: function (res) {
        wx.redirectTo({
          url: '/pages/access/access',
        })
      }
    })
  },
  login:function(){
    var that = this;
    wx.checkSession({
      complete:function(){
        wx.login({
          success: function (res) {
            if (res.code) {
              //发起网络请求
              wx.request({
                url: that.globalData.baseUrl + '/wx/login',
                data: {
                  code: res.code
                },
                success: function (res) {
                  var data = res.data.data;
                  wx.setStorageSync('sessionkey', data);
                  that.chcekUserExist(data);
                }
              })
            } else {
              console.log('获取用户登录态失败！' + res.errMsg)
            }
          }
        });
      },
    });
  },
  chcekUserExist: function (sessionkey) {
    var that = this;
    wx.request({
      url: that.globalData.baseUrl +'/user/wx/check_user_exist?sessionKey=' + sessionkey,
      success: function (res) {
        var data = res.data.data;
        if (!data) {
          wx.redirectTo({
            url: '/pages/login/login',
          });
        }
      }
    });
  }
})